package bueu.bexl.utils;

import java.lang.reflect.Array;
import java.util.Collection;

import bueu.bexl.BexlException;

public class TypeUtils {
	
	public static final boolean booleanValue(final Object value) {
		if (value == null) return false;
		
		if (value instanceof Boolean) return (Boolean) value;
		
		if (value instanceof Number) return ((Number) value).doubleValue() != 0;
		
		if (value.getClass().isArray()) return Array.getLength(value) != 0;
		
		if (value instanceof Collection) return ((Collection<?>) value).size() != 0;
		
		return value.toString().trim().length() != 0;
	}
	
	public static final double numberValue(final Object value) {
		if (value == null) return 0;
		
		if (value instanceof Number) return ((Number) value).doubleValue();
		
		String st = stringValue(value);

		try {
			return st == null? 0 : Double.parseDouble(st);
		} catch(NumberFormatException e) {
			throw new BexlException(e);
		}
	}
	
	public static final String stringValue(final Object value) {
		if (value == null) return null;
		
		if (value instanceof String) return (String) value;

		if (value.getClass().isArray()) {
			return Array.getLength(value) == 0? null : stringValue(Array.get(value, 0));
		}
		
		if (value instanceof Collection) {
			final Collection<?> collection = (Collection<?>) value;

			 //Esto es mas rapido q un toArray
			return collection.size() == 0? null : stringValue(collection.iterator().next());
		}
		
		final String st = value.toString();

		return value instanceof Double && st.endsWith(".0")? st.substring(0, st.length() - 2) : st;
	}
	
	public static final boolean isSimple(Class<?> type) {
		return type.isPrimitive() || type.isEnum()
		|| String.class.isAssignableFrom(type)
		|| Number.class.isAssignableFrom(type)
		|| Character.class.isAssignableFrom(type); 
	}
}
